package com.easy.dfc.web;

import com.alibaba.fastjson.JSONObject;
import com.easy.core.web.BaseController;
import com.easy.dfc.Utils.JsonUtil;
import com.easy.dfc.Utils.SensitivewordEngine;
import com.easy.dfc.Utils.Util;
import com.easy.dfc.Utils.Error;
import com.easy.dfc.mapper.SensitiveWordsMapper;
import com.easy.dfc.entity.ProductReply;
import com.easy.dfc.entity.ProductReplyImgs;
import com.easy.dfc.entity.SellerReplyForProductReply;
import com.easy.dfc.service.ProductReplyService;
import com.easy.dfc.service.UsersetService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping(value = "${apiPath}/productReply", method = RequestMethod.POST)
public class ProductReplyController extends BaseController {

    @Resource
    private ProductReplyService productReplyService;

    //@Resource
    //private SensitiveWordsMapper sensitiveWordsMapper;

    @Resource
    private UsersetService usersetService;

    /**
     * 发布宝贝评论
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "addProductReply", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> addQuestion(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            ProductReply productReply = new ProductReply();
            productReply.setUserid(Util.ToUuidString(userId.replaceAll("-", "")));
            productReply.setProductid(Util.ToUuidString(request.getParameter("ProductId").replaceAll("-", "")));
            productReply.setStarlevel(Float.parseFloat(request.getParameter("StarLevel")));
            //进行敏感词处理
            //productReply.setContent(SensitivewordEngine.DealWithSensitiveword(sensitiveWordsMapper, Util.getRequestString(request.getParameter("Reply"))));
            productReply.setCreated(new Date());
            productReplyService.insertSelective(productReply);
            int replyId = productReply.getId();
            List<ProductReplyImgs> productReplyImgs = new ArrayList<>();
            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();

                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null && file.getSize() > 0) {
                        String key = new Date().getTime() + file.getOriginalFilename();
                        Util.OSSUpload("replyimgs", key, file.getInputStream());
                        String path = "http://replyimgs.oss-cn-shanghai.aliyuncs.com/" + key;
                        ProductReplyImgs productReplyImgs1 = new ProductReplyImgs();
                        productReplyImgs1.setProductreplyid(replyId);
                        productReplyImgs1.setUrl(path);
                        productReplyImgs.add(productReplyImgs1);
                    }
                }
                productReplyService.insertList(productReplyImgs);
            }
            jsonObject.put("Err", Error.OK);
        } catch (IOException e) {
            jsonObject.put("Err", Error.UploadFaild);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 查看宝贝评价星级
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getProductStarLevel", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> getProductStarLevel(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            Float starLevel = productReplyService.selectAvg(request.getParameter("ProductId"));
            jsonObject.put("Err", Error.OK);
            jsonObject.put("starLevel", starLevel);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 卖家回复
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "replyForProductReply", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> replyForProductReply(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            SellerReplyForProductReply sellerReplyForProductReply = new SellerReplyForProductReply();
            //进行敏感词处理
            //sellerReplyForProductReply.setContent(SensitivewordEngine.DealWithSensitiveword(sensitiveWordsMapper, Util.getRequestString(request.getParameter("Reply"))));
            sellerReplyForProductReply.setProductreplyid(Integer.parseInt(request.getParameter("ProductReplyId")));
            sellerReplyForProductReply.setCreated(new Date());
            productReplyService.insertSelective(sellerReplyForProductReply);
            jsonObject.put("Err", Error.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 获取评论列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getProductReplyList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> getProductReplyList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            int page = Integer.parseInt(request.getParameter("Page"));
            String productId = request.getParameter("ProductId");
            //分页
            List<ProductReply> productReplies = productReplyService.selectByProductId(productId, (page - 1) * 20);
            for (ProductReply p : productReplies) {
                p.setProductReplyImgs(productReplyService.selectByProductReplyId(p.getId()));
            }
            String str = JSONObject.toJSONString(productReplies);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }
}
